import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;

//二刷
class Solution1 {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        Queue<Integer> keys = new ArrayDeque<Integer>();
        keys.offer(0);
        boolean[] visited = new boolean[rooms.size()];
        visited[0] = true;
        int count = 0;
        while (!keys.isEmpty()) {
            int key = keys.poll();
            count++;
            if (count == rooms.size()) {
                return true;
            }
            for (int nextKey : rooms.get(key)) {
                if (!visited[nextKey]) {
                    keys.offer(nextKey);
                    visited[nextKey] = true;
                }
            }
            System.out.println(Arrays.toString(visited));
        }
        return false;
    }
}

class Solution {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        boolean[] visited = new boolean[rooms.size()];
        int num = dfs(rooms, 0, visited);
        assert num <= rooms.size();
        return num == rooms.size();
    }

    private int dfs(List<List<Integer>> rooms, int i, boolean[] visited) {
        visited[i] = true;
        List<Integer> keys = rooms.get(i);
        int num = 1;
        for (int key : keys) {
            if (!visited[key]) {
                num += dfs(rooms, key, visited);
            }
        }
        return num;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}